using System;
using System.Collections;
using Sedna.Core;
using Sedna.Core.Common.Objects.Navigation;

namespace Sedna.Util
{
    public class PropertyComparer : IComparer
    {
        private String compareProperty;
		private bool isAsc;

		public PropertyComparer(String compareProperty, bool isAsc)
        {
            this.compareProperty = compareProperty;
            this.isAsc = isAsc;
        }

        public int Compare(Object x, Object y)
        {
            Object valueX = ScopePathParser.Instance.Parse(x, compareProperty).Value;
            Object valueY = ScopePathParser.Instance.Parse(y, compareProperty).Value;

            if ((valueX is IComparable) && valueY != null)
            {
                return (isAsc ? 1 : -1) * ((IComparable)valueX).CompareTo(valueY);
            }
            else if (valueX == null || valueY == null)
            {
                return (isAsc ? 1 : -1) * ((valueX == null && valueY != null ? -1 : 0) + (valueX != null && valueY == null ? 1 : 0));
            }

            throw new SednaException("Can`t compare non comparable values");
        }
    }
}
